package com.wnhz.work.jy.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import com.wnhz.work.jy.BaseActivity;
import com.wnhz.work.jy.MyApplication;
import com.wnhz.work.jy.R;
import com.wnhz.work.jy.utils.ConfigUtil;
import com.wnhz.work.jy.utils.ImageFactory;
import com.wnhz.work.jy.utils.MyUtils;
import com.wnhz.work.jy.utils.xutils3.MyCallBack;
import com.wnhz.work.jy.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * ---账户管理
 */
public class AdminAccountActivity extends BaseActivity implements View.OnClickListener {
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 412;
    private TextView title;
    private final int FROM_NAME_CODE = 653;
    private final int FROM_SEX_CODE = 663;
    private final int FROM_BIRTHDAY_CODE = 673;
    private static final int ACTIVITY_RESULT_FOR_UPDATE = 110;
    private final int FROM_WHEEL_CODE = 642;
    private String pickIndex, pickCard;

    private ImageView iv_head;
    private Bitmap head;//头像Bitmap
    private static String path = "/sdcard/myHead/";//sd路径

    private TextView tv_birthday, tv_sex, tv_address, tv_userName;

    private String province;
    private String city;
    private String district;

    private String newName;
    private String newSex;
    private String newBirthday;

    private String headPath;
    ImageOptions options = new ImageOptions.Builder()
            //设置加载过程中的图片
            .setLoadingDrawableId(R.mipmap.ic_morentouxiang)
            //设置加载失败后的图片
            .setFailureDrawableId(R.mipmap.ic_morentouxiang)
            //设置使用缓存
            .setUseMemCache(true)
            //设置显示圆形图片
            .setCircular(true)
            //设置支持gif
            .setIgnoreGif(false)
            .build();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_account);

        initData();
        initView();
    }

    private void initData() {
    }

    private void initView() {
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("账户管理");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        findViewById(R.id.rl_change_head).setOnClickListener(this);//修改头像
        findViewById(R.id.rl_userName).setOnClickListener(this);//用户名
        findViewById(R.id.rl_sex).setOnClickListener(this);//性别
        findViewById(R.id.rl_birthday).setOnClickListener(this);//出生日期
//        findViewById(R.id.rl_address).setOnClickListener(this);//地址管理
        findViewById(R.id.tv_exit).setOnClickListener(this);//退出
        findViewById(R.id.rl_pay_password).setOnClickListener(this);//支付密码
        findViewById(R.id.rl_password).setOnClickListener(this);//密码
        findViewById(R.id.rl_phone).setOnClickListener(this);//手机号

        iv_head = (ImageView) findViewById(R.id.iv_head);


        //SharedPreferences sp = this.getSharedPreferences("headPath", Context.MODE_PRIVATE);
        /*headPath = sp.getString("headPath", null);
        if (headPath != null) {
            Bitmap bt = BitmapFactory.decodeFile(headPath);//从Sd中找头像，转换成Bitmap
            if (bt != null) {
                @SuppressWarnings("deprecation")
                Drawable drawable = new BitmapDrawable(bt);//转换成drawable
                iv_head.setImageDrawable(drawable);
            } else {
                *//**
         *	如果SD里面没有则需要从服务器取头像，取回来的头像再保存在SD中
         *
         *//*
            }
        }*/
        /*Bitmap bt = BitmapFactory.decodeFile(path + "head.jpg");//从Sd中找头像，转换成Bitmap
        if (bt != null) {
            @SuppressWarnings("deprecation")
            Drawable drawable = new BitmapDrawable(bt);//转换成drawable
            iv_head.setImageDrawable(drawable);
        } else {
            *//**
         *	如果SD里面没有则需要从服务器取头像，取回来的头像再保存在SD中
         *
         *//*
        }*/

        tv_userName = (TextView) findViewById(R.id.tv_userName);
        tv_birthday = (TextView) findViewById(R.id.tv_birthday);
        tv_sex = (TextView) findViewById(R.id.tv_sex);
        tv_address = (TextView) findViewById(R.id.tv_address);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (MyApplication.getInstance().userBean != null) {
            tv_sex.setText(MyApplication.getInstance().userBean.getSex());
            tv_userName.setText(MyApplication.getInstance().userBean.getUserName());
            tv_birthday.setText(MyApplication.getInstance().userBean.getBirthday());
            x.image().bind(iv_head, MyApplication.getInstance().userBean.getUserImg(), options);
        }

    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;

            //修改头像
            case R.id.rl_change_head:
                showpopmwnu();
                break;

            //用户名
            case R.id.rl_userName:
                String oldName = tv_userName.getText().toString();
                intent = new Intent(AdminAccountActivity.this, NicknameActivity.class);
                intent.putExtra("oldName", oldName);
                startActivityForResult(intent, FROM_NAME_CODE);
                break;

            //性别
            case R.id.rl_sex:
                String oldSex = tv_sex.getText().toString();
                intent = new Intent(AdminAccountActivity.this, UserSexActivity.class);
                intent.putExtra("oldSex", oldSex);
                startActivityForResult(intent, FROM_SEX_CODE);
                break;

            //出生日期
            case R.id.rl_birthday:
                String oldBirthday = tv_birthday.getText().toString();
                intent = new Intent(AdminAccountActivity.this, UserBirthdayActivity.class);
                intent.putExtra("oldBirthday", oldBirthday);
                startActivityForResult(intent, FROM_BIRTHDAY_CODE);
//                MyDatePicker datePicker = new MyDatePicker(this);
//                datePicker.selectDateDialog(tv_birthday, "1992-01-01");
                break;

            //地址管理
          /*  case R.id.rl_address:
                intent = new Intent(this, WheelActivity.class);
                startActivityForResult(intent, FROM_WHEEL_CODE);
                break;*/

            //退出
            case R.id.tv_exit:
                MyApplication.getInstance().bean = null;
                MyApplication.getInstance().bean1 = null;
                MyApplication.getInstance().userBean = null;
                MyApplication.getInstance().removerUser();
                intent = new Intent(this, LoginActivity.class);
                startActivity(intent);
                finish();
                break;

            //支付密码
            case R.id.rl_pay_password:
                intent = new Intent(this, PayPasswordActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_phone:
                intent = new Intent(this, PayPasswordActivity.class);
                intent.putExtra("type", "手机号");
                startActivity(intent);
                break;
            case R.id.rl_password:
                intent = new Intent(this, PayPasswordActivity.class);
                intent.putExtra("type", "更换密码");
                startActivity(intent);
                break;

            default:
                break;
        }
    }

    private void showpopmwnu() {

        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                //ActivityCompat.requestPermissions(AdminAccountActivity.this, new String[]{Manifest.permission.CAMERA}, 222);
                requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, CONTEXT_INCLUDE_CODE);
                return;
            } else {
                Intent selectPhotoIntent = new Intent(AdminAccountActivity.this, SelectPhotoActivity.class);
                startActivityForResult(selectPhotoIntent, ACTIVITY_RESULT_FOR_UPDATE);
            }
        } else {
            Intent selectPhotoIntent = new Intent(AdminAccountActivity.this, SelectPhotoActivity.class);
            startActivityForResult(selectPhotoIntent, ACTIVITY_RESULT_FOR_UPDATE);
        }
        /*if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED
                *//*&& ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this,
                Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS)
                != PackageManager.PERMISSION_GRANTED*//*) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_CALL_PHONE);

        } else {
            Intent selectPhotoIntent = new Intent(AdminAccountActivity.this, SelectPhotoActivity.class);
            startActivityForResult(selectPhotoIntent, ACTIVITY_RESULT_FOR_UPDATE);
        }*/

//        startActivity(selectPhotoIntent);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            //姓名
            case FROM_NAME_CODE:
                if (resultCode == RESULT_OK) {
                    newName = data.getExtras().getString("newName");
                    tv_userName.setText(newName);
                }
                break;

            //性别
            case FROM_SEX_CODE:
                if (resultCode == RESULT_OK) {
                    newSex = data.getExtras().getString("newSex");
                    tv_sex.setText(newSex);
                }
                break;

            //生日
            case FROM_BIRTHDAY_CODE:
                if (resultCode == RESULT_OK) {
                    newBirthday = data.getExtras().getString("newBirthday");
                    tv_birthday.setText(newBirthday);
                }
                break;

            case ACTIVITY_RESULT_FOR_UPDATE:
                if (resultCode == RESULT_OK) {
                    String head1 = data.getStringExtra("head");
//                    System.out.println(head1 + "======head");
                    String from = data.getExtras().getString("from");
                    if ("1".equals(from)) {
//                        File t = new File(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "image");
//                        cropPhoto(Uri.fromFile(t));
                        headPath = "file://" + head1;

                        headPath = head1;


                        myPut(headPath);

                       /* Bitmap bt = BitmapFactory.decodeFile(headPath);//从Sd中找头像，转换成Bitmap
                        if (bt != null) {
                            @SuppressWarnings("deprecation")
                            Drawable drawable = new BitmapDrawable(bt);//转换成drawable
                            iv_head.setImageDrawable(drawable);
                        } else {
                            *//**
                         *	如果SD里面没有则需要从服务器取头像，取回来的头像再保存在SD中
                         *
                         *//*
                        }*/
                        //ImageLoader.getInstance().displayImage(headPath, iv_head);
                    } else {
                        File temp = new File(Environment.getExternalStorageDirectory()
                                + "/head.jpg");
                        cropPhoto(Uri.fromFile(temp));
                    }
                }
                break;

            case 3:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    head = extras.getParcelable("data");
                    if (head != null) {
                        /**
                         * 上传服务器代码
                         */
                        setPicToView(head);//保存在SD卡中
                        //iv_head.setImageBitmap(head);//用ImageView显示出来

                        headPath = path + "head.jpg";//图片名字
                        myPut(headPath);
                    }
                }
                break;

            //地址管理
           /* case FROM_WHEEL_CODE:
                if (resultCode == RESULT_OK) {
                    province = data.getExtras().getString("province");
                    city = data.getExtras().getString("city");
                    district = data.getExtras().getString("district");

                    tv_address.setText(province + city + district);
                }

                break;*/

            default:
                break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 调用系统的裁剪
     *
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        FileOutputStream b = null;
        File file = new File(path);
        file.mkdirs();// 创建文件夹
        headPath = path + "head.jpg";//图片名字

        try {
            b = new FileOutputStream(headPath);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
//        } finally {
//            try {
//                //关闭流
////                b.flush();
////                b.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            //就像onActivityResult一样这个地方就是判断你是从哪来的。
            case CONTEXT_INCLUDE_CODE:
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    MyToast("很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。");
                } else if (grantResults[1] != PackageManager.PERMISSION_GRANTED) {
                    MyToast("很遗憾你把访问sd卡权限禁用了。请务必开启相机权限享受我们提供的服务吧。");
                } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    Intent selectPhotoIntent = new Intent(AdminAccountActivity.this, SelectPhotoActivity.class);
                    startActivityForResult(selectPhotoIntent, ACTIVITY_RESULT_FOR_UPDATE);
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

    private void myPut(String headPath) {
        long timestamp = System.currentTimeMillis();
        String time = formatter.format(new Date());
        String fileName = "crash-" + time + "-" + timestamp + ".png";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String path = "/sdcard/crash/";
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }

        path = "/sdcard/crash/" + fileName;
        if (ImageFactory.compressPicture(headPath, path))
            sethead(path);
        else
            sethead(headPath);
    }

    private static final String TAG = "AdminAccountActivity";

    private void sethead(final String path) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", MyApplication.getInstance().userBean.getUserId());
        map.put("photoname", new File(path));
        showDialog();
        XUtil.Post(ConfigUtil.MODIFY_PHOTO, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e(TAG, "onSuccess: " + result);
                try {
                    JSONObject json = new JSONObject(result);
                    String re = json.optString("result");
                    if ("1".equals(re)) {
                        MyUtils.deleteFile(new File(path));
                        String info = json.optString("info");
                        MyToast(info);
                        String url = json.optString("url");
                        MyApplication.getInstance().userBean.setUserImg(url);
                        x.image().bind(iv_head, MyApplication.getInstance().userBean.getUserImg(), options);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }
        });
    }

}
